import { Request, Response } from 'express';
import { WeworkService } from '../services/wework.service';
import { PasswordService } from '../services/password.service';
import jwt from 'jsonwebtoken';
import { weworkConfig } from '../config/wework';
import { AppError } from '../middlewares/errorHandler';
import { pool } from '../config/database';

export class AuthController {
  private weworkService: WeworkService;
  private passwordService: PasswordService;

  constructor() {
    this.weworkService = WeworkService.getInstance();
    this.passwordService = PasswordService.getInstance();
  }

  // 账号密码登录
  login = async (req: Request, res: Response) => {
    const { username, password } = req.body;

    if (!username || !password) {
      throw new AppError('用户名和密码不能为空', 400);
    }

    try {
      // 查询用户
      const [rows] = await pool.query(
        'SELECT * FROM users WHERE username = ? AND login_type = ?',
        [username, 'account']
      );

      const user = rows[0];
      if (!user) {
        throw new AppError('用户不存在', 404);
      }

      // 验证密码
      const isValid = await this.passwordService.verifyPassword(password, user.password);
      if (!isValid) {
        throw new AppError('密码错误', 400);
      }

      // 生成JWT令牌
      const token = jwt.sign(
        {
          userId: user.id,
          name: user.name,
          isAdmin: user.is_admin
        },
        process.env.JWT_SECRET!,
        { expiresIn: process.env.JWT_EXPIRES_IN }
      );

      // 返回用户信息和令牌
      res.json({
        token,
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          avatar: user.avatar,
          isAdmin: user.is_admin,
          email: user.email
        }
      });
    } catch (error) {
      throw new AppError('登录失败', 401);
    }
  };

  // 修改密码
  changePassword = async (req: Request, res: Response) => {
    const { oldPassword, newPassword } = req.body;
    const userId = req.user?.id;

    if (!userId) {
      throw new AppError('未授权', 401);
    }

    if (!oldPassword || !newPassword) {
      throw new AppError('旧密码和新密码不能为空', 400);
    }

    await this.passwordService.changePassword(userId, oldPassword, newPassword);
    res.json({
      success: true,
      message: '密码修改成功'
    });
  };

  // 重置密码
  resetPassword = async (req: Request, res: Response) => {
    const { userId, newPassword } = req.body;

    // 检查权限
    const currentUserId = req.user?.id;
    if (!currentUserId) {
      throw new AppError('未授权', 401);
    }

    const [rows] = await pool.query(
      'SELECT is_admin FROM users WHERE id = ?',
      [currentUserId]
    );

    if (!rows[0]?.is_admin) {
      throw new AppError('没有权限执行此操作', 403);
    }

    await this.passwordService.resetPassword(userId, newPassword);
    res.json({
      success: true,
      message: '密码重置成功'
    });
  };

  // 获取企业微信登录URL
  getLoginUrl = (req: Request, res: Response) => {
    const url = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${weworkConfig.corpId}&agentid=${weworkConfig.agentId}&redirect_uri=${encodeURIComponent(weworkConfig.redirectUri)}&state=${weworkConfig.state}`;
    
    res.json({
      url,
      state: weworkConfig.state
    });
  };

  // 处理企业微信回调
  handleCallback = async (req: Request, res: Response) => {
    const { code, state } = req.query;

    if (!code || state !== weworkConfig.state) {
      throw new AppError('Invalid authorization code', 400);
    }

    try {
      // 获取用户信息
      const userInfo = await this.weworkService.getUserInfo(code as string);
      
      if (!userInfo) {
        throw new AppError('Failed to get user info', 401);
      }

      // 生成JWT令牌
      const token = jwt.sign(
        { 
          userId: userInfo.userid,
          name: userInfo.name,
          department: userInfo.department
        },
        process.env.JWT_SECRET!,
        { expiresIn: process.env.JWT_EXPIRES_IN }
      );

      // 返回用户信息和令牌
      res.json({
        token,
        user: {
          id: userInfo.userid,
          name: userInfo.name,
          avatar: userInfo.avatar,
          department: userInfo.department,
          position: userInfo.position,
          mobile: userInfo.mobile,
          email: userInfo.email
        }
      });
    } catch (error) {
      throw new AppError('Authentication failed', 401);
    }
  };
} 